<?php namespace Common\Model;
use Hdphp\Model\Model;
class User extends Model{
	protected $table = 'user';
//	注册信息的自动验证
	protected $validate = array(
		array('username','required','用户名不能为空',3,3),
		array('username','user:5,20','用户名不能少于5个且不能超过20个字符',3,3),
		array('password','required','密码不能为空',3,3),
		array('password','minlen:5','密码不能少于5位',3,3),
		array('password','regexp:/^[A-Za-z0-9_-]+$/is ','密码只能是数字，字母，下划线',3,3),
		array('password2','required','验证密码不能为空',3,3),
		array('password2','minlen:5','密码不能少于5位',3,3),
		array('email','required','邮箱不能为空',3,3),
		array('email','email','输入的邮箱不正确',3,3)
	);
//	自动完成注册时间
	protected $auto = array(
		array('regtime','time','function',3,1)
	);
	
//	用户注册
	public function reg(){
//		自动完成验证
		if(!$this->create()) return false;
//		密码验证
		if(Q('post.password')!=Q('post.password2')){
			$this->error = "两次密码不一致";
			return FALSE;
		}else{
//		存的是$this->data[]而不是$_POST
			$this->data['password'] = Q('post.password','','md5');
		}
		
//		判断用户是否已经存在
		$userData = $this->field('username')->get();
		foreach ($userData as $v) {
			if(Q('post.username')==$v['username']){
				$this->error = "该用户名已注册！";
				return FALSE;
			}
		}
		
//		判断验证码
		if(strtoupper(Q('post.mcode'))!=Code::get()){
			$this->error = "验证码错误！";
			return FALSE;
		}
//		存入数据
		$this->add();
		return TRUE;
	}

//	用户登陆
	public function login(){
//  		获得提交过来的数据
			$username = Q('post.username');
			$password = Q('post.password','','md5');
//			获得数据
			$userData = $this->where("username = '{$username}' or email = '{$username}' ")->find();
//			判断用户是否存在
			if(!$userData){
				$this->error = '用户名不存在！';
				return FALSE;
			};
//			判定密码是否正确
			if($userData['password']!=$password){
				$this->error = '密码错误！';
				return false;
			};
//			存入session
			$_SESSION['uid'] = $userData['uid'];
			$_SESSION['username'] = $userData['username'];
//			显示登陆成功
			return true;
	}
//	修改密码
	public function changePwd(){
		$data = Q('post.');
		if(empty($data['old_pwd'])||empty($data['new_pwd'])||empty($data['confirm_pwd'])){
			$this->error = '输入有误！';
			return false;
		};
		if($data['new_pwd'] !== $data['confirm_pwd']){
			$this->error = '两次密码不一致！';
			return false;
		}
//		密码正则
		$preg = "/^[A-Za-z0-9_-]{5,}$/is";
		$bool = preg_match($preg, $data['new_pwd']);
		if(!$bool){
			$this->error = "密码输入有误";
			return false;
		}
//		用户id
		$uid = $_SESSION['uid'];
		$pwd = $this->where("uid = {$uid}")->pluck('password');
		if(md5($data['old_pwd'])!==$pwd){
			$this->error = '密码不正确';
			return false;
		}
//		更新密码
		$this->where("uid = {$uid}")->save(array('password'=>md5($data['new_pwd'])));
		return true;
	}
	
	
	
	
	
	
	
	
	
}
 ?>